﻿using ILRuntime.Runtime.Enviorment;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class Main : MonoBehaviour {

    public static AppDomain appdomain;
    System.IO.MemoryStream fs;
    System.IO.MemoryStream p;

    void Start()
    {
        Debug.Log("unity start");
        StartCoroutine(LoadHotFixAssembly());
    }

    IEnumerator LoadHotFixAssembly()
    {
        appdomain = new ILRuntime.Runtime.Enviorment.AppDomain();

#if UNITY_ANDROID
        WWW www = new WWW(Application.streamingAssetsPath + "/HotFix_Project.dll");
#else
        WWW www = new WWW("file:///" + Application.streamingAssetsPath + "/HotFix_Project.dll");
#endif
        while (!www.isDone)
        {
            yield return null;//等待一帧
        }
        if (!string.IsNullOrEmpty(www.error))
        {
            UnityEngine.Debug.LogError(www.error);
        }
        byte[] dll = www.bytes;
        www.Dispose();

        //PDB文件是调试数据库，如需要在日志中显示报错的行号，则必须提供PDB文件，不过由于会额外耗用内存，正式发布时请将PDB去掉，下面LoadAssembly的时候pdb传null即可
#if UNITY_ANDROID
        www = new WWW(Application.streamingAssetsPath + "/HotFix_Project.pdb");
#else
        www = new WWW("file:///" + Application.streamingAssetsPath + "/HotFix_Project.pdb");
#endif
        while (!www.isDone)
        {
            yield return null;
        }
        if (!string.IsNullOrEmpty(www.error))
        {
            UnityEngine.Debug.LogError(www.error);
        }
        byte[] pdb = www.bytes;
        www.Dispose();

        fs = new MemoryStream(dll);
        p = new MemoryStream(pdb);
        appdomain.LoadAssembly(fs, p, new ILRuntime.Mono.Cecil.Pdb.PdbReaderProvider());
        appdomain.DebugService.StartDebugService(56000);
        InitializeILRuntime();
        OnHotFixLoaded();
    }

    void InitializeILRuntime()
    {
        //这里做一些ILRuntime的注册，暂时没有需要注册的
        RegisterAdaptor.RegisterCrossBindingAdaptor();
        RegisterCLRMethod.RegisterCLRMethodRedirection();
        RegisterDelegate.RegisterDelegateConvertor();
        //这里做一些ILRuntime的注册，这里我们对LitJson进行注册
        LitJson.JsonMapper.RegisterILRuntimeCLRRedirection(appdomain);
        //请在生成了绑定代码后解除下面这行的注释
        ILRuntime.Runtime.Generated.CLRBindings.Initialize(appdomain);
    }

    void OnHotFixLoaded()
    {
        Debug.Log("Unity Invoke HotFix_Project.Main.Run()");
        appdomain.Invoke("HotFix_Project.Main", "Run", null, null);
    }
}
